<template>
  <div>
    <h1>{{ '学校详情' }}</h1>
    <el-divider></el-divider>
    <el-row :gutter="20">
      <el-col :span="8">
        <div style="width: 150px; height: 150px; overflow: hidden">
          <img width="150" :src="schoolInfo.schoolImageUrl" alt="" />
        </div>
      </el-col>
      <el-col :span="8">
        <p>学校名称：{{ schoolInfo.schoolName }}</p>
        <p>学校性质：{{ schoolInfo.schoolType }}</p>
        <p>学生规模：{{ schoolInfo.studentScale }}</p>
      </el-col>
      <el-col :span="8">
        <p>所属地区：{{ schoolInfo.address }}</p>
        <p>覆盖年级：{{ schoolInfo.grade }}</p>
        <p>教师规模：{{ schoolInfo.teacherScale }}</p>
      </el-col>
    </el-row>
    <h2>教师Launch</h2>
    <el-divider></el-divider>
    <el-table :data="teacherLaunchList" style="width: 100%">
      <el-table-column label="版本">
        <template slot-scope="scope">
          <span>{{
            `${scope.row.version}（${scope.row.versionNumber}）`
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户数">
        <template slot-scope="scope">
          <span>{{ scope.row.userCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新内容">
        <template slot-scope="scope">
          <pre
            style="
              font-family: 'Helvetica Neue', Helvetica, 'PingFang SC',
                'Hiragino Sans GB', 'Microsoft YaHei', '\5FAE\8F6F\96C5\9ED1',
                Arial, sans-serif;
            "
            >{{ scope.row.remark }}</pre
          >
        </template>
      </el-table-column>
      <el-table-column label="最近上线时间">
        <template slot-scope="scope">
          <span>{{ scope.row.onlineTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="
              onlineLaunchVisible = true
              launchType = 2
            "
            >版本上线</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <h2>学生Launch</h2>
    <el-divider></el-divider>
    <el-table :data="studentList" style="width: 100%">
      <el-table-column label="版本">
        <template slot-scope="scope">
          <span>{{
            `${scope.row.version}（${scope.row.versionNumber}）`
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户数">
        <template slot-scope="scope">
          <span>{{ scope.row.userCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新内容">
        <template slot-scope="scope">
          <pre
            style="
              font-family: 'Helvetica Neue', Helvetica, 'PingFang SC',
                'Hiragino Sans GB', 'Microsoft YaHei', '\5FAE\8F6F\96C5\9ED1',
                Arial, sans-serif;
            "
            >{{ scope.row.remark }}</pre
          >
        </template>
      </el-table-column>
      <el-table-column label="最近上线时间">
        <template slot-scope="scope">
          <span>{{ scope.row.onlineTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="
              onlineLaunchVisible = true
              launchType = 1
              selectLaunchId = scope.row.id
            "
            >版本上线</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <h2>
      学生APP<el-button
        style="float: right"
        type="primary"
        @click="
          appType = 1
          onlineAppVisible = true
        "
        >开通学生APP</el-button
      >
    </h2>
    <el-divider></el-divider>
    <div>
      <div>
        <el-button
          style="margin-bottom: 15px"
          type="primary"
          @click="onlineApp(1)"
          >更新版本</el-button
        >
      </div>
      <el-radio-group v-model="selectStuApp" @change="stuAppChange">
        <el-radio-button
          v-for="app in studentAppList"
          :key="app.id"
          :label="app.newAppVersionId"
          >{{ app.appName }}</el-radio-button
        >
      </el-radio-group>
      <div v-for="(grade, index) in gradeList" :key="grade.gradeId">
        <el-checkbox
          style="margin-top: 10px"
          :indeterminate="grade.isIndeterminate"
          v-model="grade.isCheck"
          @change="checkTitle(grade.isCheck, index)"
          >{{ grade.gradeName }}</el-checkbox
        >
        <div style="margin: 15px 0"></div>
        <el-checkbox-group
          v-model="grade.checkedData"
          @change="checkItem(grade.checkedData, index)"
        >
          <el-checkbox
            v-for="classes in grade.classesVoList"
            :label="classes.classesId"
            :key="classes.classesId"
            >{{ classes.classesName }}（{{ classes.appVersion }}）</el-checkbox
          >
        </el-checkbox-group>
      </div>
    </div>
    <h2>
      教师APP<el-button
        style="float: right"
        type="primary"
        @click="
          appType = 2
          onlineAppVisible = true
        "
        >开通教师APP</el-button
      >
    </h2>
    <el-divider></el-divider>
    <div>
      <div>
        <el-button
          style="margin-bottom: 15px"
          type="primary"
          @click="onlineApp(2)"
          >更新版本</el-button
        >
      </div>
      <el-radio-group v-model="selectTecApp">
        <el-radio-button
          v-for="app in teacherAppList"
          :key="app.id"
          :label="app.newAppVersionId"
          >{{ app.appName }}</el-radio-button
        >
      </el-radio-group>
      <div>
        <el-checkbox
          style="margin-top: 10px"
          :indeterminate="teacherList.isIndeterminate"
          v-model="teacherList.isCheck"
          @change="checkTeacherTitle(teacherList.isCheck)"
          >全选</el-checkbox
        >
        <div style="margin: 15px 0"></div>
        <el-checkbox-group
          v-model="teacherList.checkedData"
          @change="checkTeacherItem(teacherList.checkedData)"
        >
          <el-checkbox
            v-for="grade in teacherList.teacherList"
            :label="grade.id"
            :key="grade.id"
            >{{
              `${grade.realName}（${grade.gradeList.join('、')} ${
                grade.subject
              }）`
            }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
    </div>
    <el-dialog title="上线launch" :visible.sync="onlineLaunchVisible">
      <school-online-launch
        :showTypeSelect="false"
        :launchTypeProp="launchType"
        :selectLaunchId="selectLaunchId"
        :schoolId="$route.query.id"
        @cancel="selectCancel"
        @change="selectChange"
      ></school-online-launch>
    </el-dialog>
    <el-dialog title="开通app" width="860px" :visible.sync="onlineAppVisible">
      <school-online-app
        :showTypeSelect="false"
        :launchTypeProp="appType"
        :schoolId="$route.query.id"
        @cancel="selectCancel"
        @change="selectAppChange"
      ></school-online-app>
    </el-dialog>
  </div>
</template>

<script>
// import base from '@/views/base.vue'
import {
  queyEnumByTableName,
  tableUpdate,
  downloadTemplateFile,
  importData
} from '@/api/api.js'
import { querySchool } from '@/api/user'
import {
  adminschoollist,
  enumschoolall,
  adminimportschoolExport
} from '@/api/lcmapi.js'
import {
  schoolInfo,
  schoolDetailLaunchList,
  schoolDetailAppList,
  getTeacherList,
  getClassesList,
  onlineApp,
  onlineLaunch
} from '@/api/launch.js'
import SchoolOnlineLaunch from './components/school-online-launch.vue'
import SchoolOnlineApp from './components/school-online-app.vue'
export default {
  name: 'launch-school',
  // extends: base,
  data () {
    return {
      selectLaunchId: null,
      launchType: 1,
      appType: 1,
      onlineLaunchVisible: false,
      onlineAppVisible: false,
      selectStuApp: null,
      selectTecApp: null,
      editableTabsValue: '2',
      editableTabs: [
        {
          title: 'Tab 1',
          name: '1',
          content: 'Tab 1 content'
        },
        {
          title: 'Tab 2',
          name: '2',
          content: 'Tab 2 content'
        }
      ],
      tabIndex: 2,
      schoolInfo: {},
      teacherLaunchList: [],
      studentList: [],
      studentAppList: [],
      teacherAppList: [],
      gradeList: [],
      teacherList: [],
      currentStuApp: null
    }
  },
  async activated () {
    this.$store.dispatch('common/saveRegion')
    // this.getDataList("", "", "", "");
    this.queyEnumByTableName()
    this.getInit()
  },
  computed: {},
  components: {
    SchoolOnlineLaunch,
    SchoolOnlineApp
  },
  async created () {
    this.getInit()
  },
  methods: {
    // 初始获取信息
    async getInit () {
      const res = await schoolInfo({ schoolId: this.$route.query.id })
      this.schoolInfo = res[1].data
      await this.schoolDetailLaunchList()
      await this.schoolDetailAppList()
      await this.getTeacherList()
      await this.getGradeList()
    },
    async selectAppChange (val) {
      let classList = []
      if (val.launchType == 1) {
        for (let i = 0; i < val.gradeList.length; i++) {
          const res = val.gradeList[i]
          for (let c = 0; c < res.checkedData.length; c++) {
            const classId = res.checkedData[c]
            classList.push({
              classesId: classId,
              gradeId: res.gradeId,
              schoolId: val.schoolId
            })
          }
        }
      } else {
        for (let i = 0; i < val.teacherList.checkedData.length; i++) {
          const classId = val.teacherList.checkedData[i]
          classList.push({
            teacherId: classId,
            schoolId: val.schoolId
          })
        }
      }
      let finialList = []
      val.appList.map(item => {
        if (item.selectBatchLaunch) {
          finialList.push({
            appVersionId: item.selectBatchLaunch,
            classesLists: classList
          })
        }
      })
      if (!finialList.length) {
        this.$message.error('请先选择app版本')
        return
      }
      if (!classList.length) {
        this.$message.error('上线对象不能为空')
      } else {
        const updateRes = await onlineApp(finialList)
        if (updateRes[0]) {
          this.$message.error(updateRes[1].message)
        } else {
          this.$message.success('上线成功')
          await this.schoolDetailAppList()
          this.onlineAppVisible = false
        }
      }
      console.log(val)
    },
    async selectChange (val) {
      if (!val.selectLaunch) {
        this.$message.error('版本不能为空')
        return
      }
      let classList = []
      if (val.launchType == 1) {
        for (let i = 0; i < val.gradeList.length; i++) {
          const res = val.gradeList[i]
          for (let c = 0; c < res.checkedData.length; c++) {
            const classId = res.checkedData[c]
            classList.push({
              classesId: classId,
              gradeId: res.gradeId,
              schoolId: val.schoolId
            })
          }
        }
      } else {
        for (let i = 0; i < val.teacherList.checkedData.length; i++) {
          const classId = val.teacherList.checkedData[i]
          classList.push({
            teacherId: classId,
            schoolId: val.schoolId
          })
        }
      }
      if (!classList.length) {
        this.$message.error('上线对象不能为空')
      } else {
        const updateRes = await onlineLaunch({
          classesLists: classList,
          launchId: val.selectLaunch
        })
        if (updateRes[0]) {
          this.$message.error(updateRes[1].message)
        } else {
          this.$message.success('上线成功')
          this.onlineLaunchVisible = false
        }
      }
      console.log(val)
    },
    selectCancel () {
      this.onlineLaunchVisible = false
      this.onlineAppVisible = false
    },
    stuAppChange () {
      const _index = this.studentAppList.findIndex(
        item => item.newAppVersionId == this.selectStuApp
      )
      this.currentStuApp = this.studentAppList[_index].id
      this.getGradeList()
    },
    async onlineApp (launchType) {
      console.log('this.select', this.selectStuApp)
      if (launchType == 1 && !this.selectStuApp) {
        this.$message.error('请先选择学生app')
        return
      }
      if (launchType == 2 && !this.selectTecApp) {
        this.$message.error('请先选择教师app')
        return
      }
      let classList = []
      if (launchType == 1) {
        for (let i = 0; i < this.gradeList.length; i++) {
          const res = this.gradeList[i]
          for (let c = 0; c < res.checkedData.length; c++) {
            const classId = res.checkedData[c]
            classList.push({
              classesId: classId,
              gradeId: res.gradeId,
              schoolId: this.$route.query.id
            })
          }
        }
      } else {
        for (let i = 0; i < this.teacherList.checkedData.length; i++) {
          const classId = this.teacherList.checkedData[i]
          classList.push({
            teacherId: classId,
            schoolId: this.$route.query.id
          })
        }
      }
      let finialList = [
        {
          appVersionId: launchType == 1 ? this.selectStuApp : this.selectTecApp,
          classesLists: classList
        }
      ]
      if (!classList.length) {
        this.$message.error('更新对象不能为空')
      } else {
        const updateRes = await onlineApp(finialList)
        if (updateRes[0]) {
          this.$message.error('更新失败')
        } else {
          this.$message.success('更新成功')
        }
      }
    },
    checkItem (val, index, sIndex) {
      console.log('item =>>', val, index)
      let checkedCount = val.length
      this.gradeList[index].isCheck =
        checkedCount === this.gradeList[index].classesVoList.length
      this.gradeList[index].isIndeterminate =
        checkedCount > 0 &&
        checkedCount < this.gradeList[index].classesVoList.length
    },
    checkTitle (val, index, sIndex) {
      console.log('title =>>', val, index)
      let arr = []
      const re = this.gradeList[index].classesVoList
      // 全选
      if (val) {
        for (let i = 0; i < re.length; i++) {
          arr[i] = re[i]['classesId']
        }
      }
      this.gradeList[index].checkedData = arr
      this.gradeList[index].isIndeterminate = false
    },
    checkTeacherItem (val, index, sIndex) {
      let checkedCount = val.length
      this.teacherList.isCheck =
        checkedCount === this.teacherList.teacherList.length
      this.teacherList.isIndeterminate =
        checkedCount > 0 && checkedCount < this.teacherList.teacherList.length
    },
    checkTeacherTitle (val, index, sIndex) {
      let arr = []
      const re = this.teacherList.teacherList
      // 全选
      if (val) {
        for (let i = 0; i < re.length; i++) {
          arr[i] = re[i]['id']
        }
      }
      this.teacherList.checkedData = arr
      this.teacherList.isIndeterminate = false
    },
    async getGradeList () {
      const gradeList = await getClassesList({
        schoolId: this.$route.query.id,
        appId: this.currentStuApp || ''
      })
      for (let index = 0; index < gradeList[1].data.length; index++) {
        const element = gradeList[1].data[index]
        element.isIndeterminate = true
        element.isCheck = false
        element.checkedData = []
      }
      this.gradeList = gradeList[1].data
    },
    async getTeacherList () {
      const teacherList = await getTeacherList({
        schoolId: this.$route.query.id
      })
      this.teacherList = {
        teacherList: teacherList[1].data,
        isIndeterminate: true,
        isCheck: false,
        checkedData: []
      }
    },
    async schoolDetailAppList () {
      const res = await schoolDetailAppList({ schoolId: this.$route.query.id })
      this.teacherAppList = res[1].data.teacher
      this.studentAppList = res[1].data.student
    },
    async schoolDetailLaunchList () {
      const res = await schoolDetailLaunchList({
        schoolId: this.$route.query.id
      })
      this.teacherLaunchList = res[1].data.teacherLaunch
      this.studentList = res[1].data.studentLaunch
    },
    removeTab (targetName) {
      let tabs = this.editableTabs
      let activeName = this.editableTabsValue
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
            }
          }
        })
      }
      this.editableTabsValue = activeName
      this.editableTabs = tabs.filter(tab => tab.name !== targetName)
    },
    // 获取枚举
    async queyEnumByTableName () {
      // 获取学校的枚举接口
      let selectArr = {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      }
      let enumschoolallRes = await enumschoolall({})
      if (enumschoolallRes[0]) {
        return
      }
      this.selectArr = enumschoolallRes[1].data
      this.selectArr.level = [
        {
          label: 'A',
          value: 1
        },
        {
          label: 'B',
          value: 2
        },
        {
          label: 'C',
          value: 3
        }
      ]
      this.selectArr.coverageGrade = [
        {
          label: '幼儿园',
          value: 1
        },
        {
          label: '小学',
          value: 2
        },
        {
          label: '初中',
          value: 3
        },
        {
          label: '高中',
          value: 4
        }
      ]
    }
  }
}
</script>
<style scoped>
.el-checkbox + .el-checkbox {
  margin-left: 0;
}
</style>
